package com.zhijian.warehouse.manage.service.impl;

import com.zhijian.autoconfigure.cache.CacheClient;
import com.zhijian.warehouse.manage.config.Constants;
import com.zhijian.warehouse.manage.service.TcpService;
import com.zhijian.warehouse.manage.tcp.TcpHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


@Service
@Slf4j
public class TcpServiceImpl implements TcpService, ApplicationContextAware {

    private TcpHandler tcpHandler;

    private ChannelHandlerContext ctx;


    private ApplicationContext applicationContext;

    @Autowired
    private CacheClient cacheClient;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void initTcpProperty(TcpHandler handler, ChannelHandlerContext context) {
        this.ctx = context;
        this.tcpHandler = handler;
    }

    /**
     * 锁
     */
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    @Override
    public void sendTcpMsg(String str, String ip) {
        str = str.replaceAll(" ", "");
        try {
            lock.lock();
            // 实际发送
            if (tcpHandler == null) {
                System.out.println("tcpHandler == null}");
                return;
            }

            System.out.println("tcp -- 发送命令 ---" + str);
            tcpHandler.downMsgSend(ip, str);
            condition.await(1, TimeUnit.SECONDS);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("tcp -- 发送命令出错");
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void changeConditionStatus(ChannelHandlerContext ctx, String tcpMsg) throws Exception {
        //DTU的ID
        String thingId = tcpMsg.substring(6);

        // 心跳、登录
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        cacheClient.setExSeconds(String.format("%s:%s", Constants.HEART_LEIYA, thingId), socketAddress.toString(), 1200);
        cacheClient.setExSeconds(socketAddress.toString(), thingId, 1200);
        log.info("心跳：{},{}", socketAddress.toString(), thingId);

    }

    /**
     * 设备上报
     *
     * @param ctx
     * @param tcpMsg
     * @throws Exception
     */
    @Override
    public void tcpUpMsgHandle(ChannelHandlerContext ctx, String tcpMsg) throws Exception {

        log.info("收到消息：{},{}", ctx.channel().remoteAddress().toString(), tcpMsg);
        //分割后的消息数组
        String[] tcpMsgArray = tcpMsg.split(";");
        ChannelId channelId = ctx.channel().id();
        if (tcpMsg.startsWith("recok")) {

        } else {

        }


    }

    @Override
    public void deviceOnline(String thingId) {
        //设备上线
//        deviceService.updateLineStatusByThingId(LineEnum.ONLINE.getCode().byteValue(), thingId);
    }


}
